<template>
  <div class="min-h-screen bg-gray-100">
    <!-- 头部标语 -->
    <header class="bg-blue-500 text-white p-4 text-center">
      <h1 class="text-xl font-bold">欢迎购买{{ orderData.ordenContent }}</h1>
    </header>

    <!-- 内容盒子 -->
    <main class="p-8">
      <div class="bg-white shadow-md p-6 rounded-md">
        <!-- 小标题 -->
        <h2 class="text-lg font-semibold mb-4">订单信息</h2>

        <!-- 表单表格 -->
        <el-table :data="orderData" border>
          <el-table-column prop="userName" label="购买名称(购买方)"></el-table-column>
          <el-table-column prop="orderContent" label="商品名称"></el-table-column>
          <el-table-column prop="totalAmount" label="价格"></el-table-column>
        </el-table>

        <!-- 协议选择 -->
        <div class="mt-4 flex items-center">
          <el-checkbox v-model="agreementChecked">
            我已阅读并同意
            <a href="#" @click.prevent="openAgreement" class="text-blue-500 underline">购买协议>></a>
          </el-checkbox>
        </div>

        <!-- 按钮 -->
        <div class="mt-6 flex justify-end space-x-4">
          <el-button @click="cancelOrder">取消订单</el-button>
          <el-button type="primary" @click="handleConfirmOrder" :disabled="!agreementChecked">确认订单</el-button>
        </div>
      </div>

      <!-- 支付说明 -->
      <div class="mt-8">
        <h2 class="text-lg font-semibold text-center mb-4">支付说明</h2>
        <p class="text-sm text-gray-600">
          1. 当您已经通过实名认证并勾选同意购买协议后，方可下单购买。<br>
          2. 请您仔细检查订单信息，准确无误后再确认订单，确认后将出现二维码，请用支付宝、微信或云闪付扫码支付。<br>

        </p>
        <!-- 支付说明图片 -->

        <div style="width: 200px; height: 200px;">
          <img :src="payImg" />
        </div>
      </div>
    </main>

    <!-- VIP会员协议弹窗 -->
    <el-dialog v-model="agreementDialogVisible" title="支付协议" width="50%">
      <template #footer>
        <el-button @click="agreementDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 支付二维码弹窗 -->
    <el-dialog v-model="paymentDialogVisible" title="正在支付，请稍等" width="30%" :before-close="handlePaymentClose">
      <div class="text-center">
        <img src="https://via.placeholder.com/150x150" alt="支付二维码" class="mx-auto mb-4" />
        <p>请使用支付宝扫码支付。</p>
      </div>
      <template #footer>
        <el-button @click="paymentSuccess">支付成功</el-button>
        <el-button @click="handlePaymentClose">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 支付失败弹窗 -->
    <el-dialog v-model="paymentFailDialogVisible" title="支付失败" width="30%">
      <div>支付失败，请重新尝试。</div>
      <template #footer>
        <el-button @click="paymentFailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 支付成功弹窗 -->
    <el-dialog v-model="paymentSuccessDialogVisible" title="支付成功" width="30%">
      <div>支付成功,已开通服务。</div>
      <template #footer>
        <el-button @click="paymentSuccessDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 取消订单确认弹窗 -->
    <el-dialog v-model="cancelDialogVisible" title="取消订单确认" width="30%">
      <div>你确定要取消订单吗？</div>
      <template #footer>
        <el-button @click="cancelDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCancelOrder">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { addOrder } from '@/api/pay/order';
import { payUrl } from '@/api/pay/pay';
import useUserStore from '@/store/modules/user';
import { onBeforeUnmount, ref, toRefs } from 'vue';
import { useRouter } from 'vue-router';
import QRCode from 'qrcode'


const router = useRouter();
const userStore = useUserStore();

const orderData = ref([router.currentRoute.value.query]);


const payImg = ref("");
const paymentSuccessDialogVisible = ref(false);
const paymentFailDialogVisible = ref(false);
const agreementChecked = ref(false);

let interval;
let ws;



function getUserInfo() {
  userStore.getInfo().then(res => {
    console.log(res);
    console.log(orderData);
    orderData.value[0].userName = res.user.userName;
    orderData.value[0].totalAmount = 0.01;
  });
}

function handleConfirmOrder() {
  addOrder(orderData.value[0]).then(res => {
    ws = new WebSocket("ws://121.41.171.121/websocket/pay/" + res.data.orderNumber);
    interval = setInterval(() => {
      console.log("定时器正常工作");
      ws.send("");
    }, 3000)
    ws.onmessage = (data) => {
      console.log(data);
      const res = JSON.parse(data.data);
      if (res.msg == "TRADE_SUCCESS") {
        paymentSuccessDialogVisible.value = true;
      } else {
        paymentFailDialogVisible.value = true;
      }
    }
    ws.onclose = () => {
      clearInterval(interval);
    }
    payUrl(res.data.orderNumber).then(res => {
      const parser = new DOMParser();
      const doc = parser.parseFromString(res.msg, 'text/html');
      const newWindow = window.open();
      newWindow.document.write(doc.documentElement.outerHTML);
      newWindow.document.close();
    })
  })
}

async function generateQRCode(url) {
  payImg.value = await QRCode.toDataURL(url);
}

onBeforeUnmount(() => {
  clearInterval(interval);
  ws.close();
})

getUserInfo()

/* 
    data() {
      return {
        agreementChecked: false,
        agreementDialogVisible: false,
        paymentDialogVisible: false,
        paymentFailDialogVisible: false,
        paymentSuccessDialogVisible: false,
        cancelDialogVisible: false,
        orderData: [
          {
            orderId: '123456',
            buyerName: '张三',
            productName: '数据分析VIP会员',
            price: '¥199.00'
          },
          {
            orderId: '123457',
            buyerName: '李四',
            productName: '数据分析VIP会员',
            price: '¥199.00'
          }
        ]
      };
    },
    methods: {
      openAgreement() {
        this.agreementDialogVisible = true;
      },
      confirmOrder() {
        this.paymentDialogVisible = true;
      },
      handlePaymentClose() {
        this.paymentDialogVisible = false;
        this.paymentFailDialogVisible = true; // 支付失败弹窗
      },
      paymentSuccess() {
        this.paymentDialogVisible = false;
        this.paymentSuccessDialogVisible = true; // 支付成功弹窗
      },
      cancelOrder() {
        this.cancelDialogVisible = true;
      },
      confirmCancelOrder() {
        // 确认取消订单，返回主页面的逻辑
        console.log('订单已取消，返回主页面');
        this.cancelDialogVisible = false;
      }
    } */

</script>

<style scoped>
/* 自定义样式 */
</style>